package cn.devices.controller;


import cn.devices.dto.SelectBorrowDto;
import cn.devices.dto.UserBorrowDto;
import cn.devices.entity.TbBorrow;
import cn.devices.model.JsonMessage;
import cn.devices.service.TbBorrowService;
import cn.devices.utils.FileUtil;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Base64;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import static cn.devices.controller.test.getFileByBytes;


/**
 * <p>
 * 设备出借表 前端控制器
 * 借出
 * </p>
 *
 * @author 秋水浮萍
 * @since 2021-02-07
 */
@RestController
@RequestMapping("/tb-borrow")
public class TbBorrowController {
    @Value("${load.upload}")
    private String uploadPath;
    @Autowired
    private TbBorrowService tbBorrowService;


    @GetMapping("getUserIdBorrow")
    public JsonMessage getUserIdBorrow(String userId) {
        JsonMessage message = new JsonMessage();
        List<TbBorrow> borrow = tbBorrowService.getUserIdBorrow(userId);
        message.setData(borrow);
        return message;
    }


    @GetMapping("borrowS")
    public JsonMessage borrowS(String deviceCode) {
        JsonMessage message = new JsonMessage();
        String borrow = tbBorrowService.borrow(deviceCode);
        message.setData(borrow);
        return message;
    }

    /**
     * 借出设备
     *
     * @param userId     用户id
     * @param deviceCode 设备编号
     * @return
     */
    @GetMapping("isBorrow")
    public JsonMessage isBorrow(String userId, String deviceCode) {
        String a="0";
        JsonMessage message = new JsonMessage();

        if (tbBorrowService.userCount(userId) == 0) {
            message.setData("该用户不存在或已注销，请更新本地数据");
            return message;
        }

        if (tbBorrowService.count(deviceCode) == 0) {
            message.setData("该设备不存在或未录入");
            return message;
        }
        //对应部门权限
        UserBorrowDto dtoDm = tbBorrowService.userBorrowDtoDm(userId, deviceCode);
        //对应个人权限
        UserBorrowDto dtoSelf = tbBorrowService.userBorrowDtoSelf(userId, deviceCode);
        //3.是否授权 有数据 授权（部门、个人）
        if (dtoDm == null && dtoSelf == null) {
            message.setData("未授权，不可借出设备");
            return message;
        }

        //1.设备是否故障
        if ((dtoSelf != null && dtoSelf.getDeviceStatus().equals("2")) ||
                (dtoDm != null && dtoDm.getDeviceStatus().equals("2"))) {
            message.setData("设备故障,不可出借");
            return message;
        }
        //2.用户状态是否可借
        if ((dtoSelf != null && dtoSelf.getUserStatus().equals("2")) ||
                (dtoDm != null && dtoDm.getUserStatus().equals("2"))) {
            message.setData("该用户不可借出设备");
            return message;
        }

        if (dtoDm != null || dtoSelf != null) {
            //可以借出设备
            TbBorrow borrow = new TbBorrow();
            borrow.setBorrowId(UUID.randomUUID().toString());
            String img = tbBorrowService.img(userId);
            borrow.setBorrowImage(img);
            borrow.setBorrowTime(new Date());
            borrow.setDeviceCode(deviceCode);
            borrow.setUserId(userId);
            tbBorrowService.tbBorrowAdd(borrow);
            //修改设备出借信息
            tbBorrowService.isBorrow("1", deviceCode, "1");


            message.setData("借出成功");
        }


        return message;
    }

    /**
     * 归还设备
     *
     * @param deviceCode //* @param file
     * @return
     */
    @PostMapping("isRecycle")
    public JsonMessage isRecycle(String deviceCode, String photo, String borrowSpec, String deviceStatus) {
        JsonMessage message = new JsonMessage();
        String a="";
        TbBorrow borrow = tbBorrowService.tbBorrowSelect(deviceCode);
        if (borrow == null) {
            message.setData("该设备不在借出状态中");
            return message;
        }

        String path = "";
        try {
            Base64.Decoder decoder = Base64.getMimeDecoder();//注不要使用.getDecoder();
            // 对base64数据进行解码 生成 字节数组，不能直接用Base64.decode（）；进行解密
            byte[] photoimg = decoder.decode(photo);
            for (int i = 0; i < photoimg.length; ++i) {
                if (photoimg[i] < 0) {
                    // 调整异常数据
                    photoimg[i] += 256;
                }
            }

            // byte[] photoimg = Base64.decode(photo);//此处不能用Base64.decode（）方法解密，我调试时用此方法每次解密出的数据都比原数据大  所以用上面的函数进行解密，在网上直接拷贝的，花了好几个小时才找到这个错误（菜鸟不容易啊）
            System.out.println("图片的大小：" + photoimg.length);
            path = uploadPath + File.separator + "back" + deviceCode + ".jpg";
            getFileByBytes(photoimg, uploadPath + File.separator + "back", deviceCode + ".jpg");

        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            message.setData("失败");
            return message;
        }


        borrow.setRetTime(new Date());
        borrow.setRetImage(path);

        borrow.setBorrowSpec(borrowSpec);
        tbBorrowService.tbBorrowUpdate(borrow);
        //修改设备出借信息
        tbBorrowService.isBorrow("0", deviceCode, deviceStatus);
        message.setData("归还成功");
        return message;
    }

    /**
     * 出借信息
     *
     * @param pageIndex
     * @param pageSize
     * @param beginTime  出借开始时间
     * @param endTime    出借结束时间
     * @param userName   用户名
     * @param telephone  用户手机号
     * @param deviceCode 设备编号
     * @param deviceName 设备名
     * @param typeId     设备类型
     * @return
     */
    @GetMapping("borrowDtoList")
    public JsonMessage borrowDtoList(@RequestParam(defaultValue = "1") int pageIndex,
                                     @RequestParam(defaultValue = "10") int pageSize,
                                     String beginTime, String endTime, String userName,
                                     String telephone, String deviceCode, String deviceName,
                                     String typeId) {
        JsonMessage message = new JsonMessage();
        PageInfo<SelectBorrowDto> page = tbBorrowService.BorrowDtoList(pageIndex, pageSize, beginTime, endTime, userName, telephone, deviceCode, deviceName, typeId);
        message.setData(page);
        return message;
    }

    //将Byte数组转换成文件
    public void getFileByBytes(byte[] bytes, String filePath, String fileName) {
        BufferedOutputStream bos = null;
        FileOutputStream fos = null;
        File file = null;
        try {
            File dir = new File(filePath);
            if (!dir.exists() && dir.isDirectory()) {// 判断文件目录是否存在
                dir.mkdirs();
            }
            file = new File(filePath + File.separator + fileName);
            fos = new FileOutputStream(file);
            bos = new BufferedOutputStream(fos);
            bos.write(bytes);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }


}
